package legumes.client.ui.basket.slate;

import java.util.Date;
import java.util.List;

import legumes.client.evt.customer.CustomerOrderChangedEvent;
import legumes.client.evt.manager.EventBusManager;
import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.SaveStallCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.widgets.utils.Formatters;
import legumes.shared.domain.Menu;
import legumes.shared.domain.MenuCount;
import legumes.shared.domain.MenuItem;
import legumes.shared.domain.OnSaleProduct;
import legumes.shared.domain.OrderPart;
import legumes.shared.domain.Price;
import legumes.shared.domain.Product;
import legumes.shared.domain.Quantity;
import legumes.shared.domain.Stall;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.Image;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.WidgetCanvas;
import com.smartgwt.client.widgets.layout.HLayout;

public class BasketPanel extends HLayout {

	private final static String NEW_ITEM_ID = "newItem";
	private FlexTable flexTableFullBasket;
	private FlexTable flexTableHalfBasket;
	
	private Stall stall;
	private OrderPart op;
	private boolean isMarketEditMode;
	private boolean firstInit = true;

	private WidgetCanvas flexTableFullBasketWidgetCanvas;
	private WidgetCanvas flexTableHalfBasketWidgetCanvas;
	
	
	public BasketPanel(boolean isMarketEditMode_){
		super();
		isMarketEditMode = isMarketEditMode_;

		setAutoHeight();
		setWidth(600);
		setAlign(Alignment.CENTER);
		
		initflexTableFullBasket();
		initflexTableHalfBasket();
		
		flexTableFullBasketWidgetCanvas =  new WidgetCanvas( new SlatePanel(flexTableFullBasket) );
		flexTableHalfBasketWidgetCanvas = new WidgetCanvas( new SlatePanel(flexTableHalfBasket) );
		
		setMembers(flexTableFullBasketWidgetCanvas,flexTableHalfBasketWidgetCanvas );
	}
	
	private void initflexTableFullBasket(){
		flexTableFullBasket = new FlexTable();
		initFlexTable(flexTableFullBasket, "wholeBasket", "Panier de la semaine");
	}
	

	private void initflexTableHalfBasket(){
		flexTableHalfBasket = new FlexTable();
		initFlexTable(flexTableHalfBasket, "halfBasket", "Demi Panier");
	}

	
	private void initFlexTable(final FlexTable ft_, final String idSuffix_, String title_ ){
		ft_.setWidth("240px");
		ft_.setCellPadding(0);
		ft_.setCellSpacing(0);
		ft_.setBorderWidth(0);
		initTableHeader(ft_, idSuffix_, title_, -1);
		
		ft_.addClickHandler(new ClickHandler() {
			
			
			private void unckedOppositeCheckBox(){
				String oppositeBasketSuffix;
    			if( ft_ == flexTableFullBasket ){
    				//if half basket is checked, we unchecked it
    				oppositeBasketSuffix = "halfBasket";
    			} else {
    				oppositeBasketSuffix = "wholeBasket";
    			}
    			
    			Element eOpposite = DOM.getElementById("checkbox." + oppositeBasketSuffix);
    			if(eOpposite != null ){
    				InputElement ieOpposite = InputElement.as(eOpposite);
    				if( ieOpposite.isChecked() ){
    					ieOpposite.setChecked(false);
    					try {
							float basketPrice = Formatters.extractFloat( eOpposite.getAttribute("basketprice") );
							EventBusManager.getInstance().getEventBus().fireEvent(
		                			new CustomerOrderChangedEvent(false, basketPrice));
						} catch (Exception e1) {
						}
    				}
    			}
			}
			
			@Override
			public void onClick(ClickEvent event) {
				Cell cell = ft_.getCellForEvent(event);
				if(cell!=null){
			        int receiverRowIndex = cell.getRowIndex();
			        int receiverColIndex = cell.getCellIndex();
			        
			        //Only on checkBox
			        if(receiverColIndex==0){
			        	
			        	//Do not take into account the header
				        if(receiverRowIndex>=3){
				        	receiverRowIndex-=3;
				        	
				        	if(receiverRowIndex == ft_.getRowCount()-1){
				        		//New product
				        	}
//					        MenuItem menuItem = menuItemList.get(receiverRowIndex);
					        
//					        Element e = DOM.getElementById("select.menuItem." + idSuffix_ + "." + menuItem.getArticleName());
//					        Element eName = DOM.getElementById("name.menuItem." + idSuffix_ + "." + menuItem.getArticleName());
//					        
//					        if( InputElement.as(e).isChecked() ){
//					        	e.removeClassName("removeMenuItem");
//					        	e.addClassName("cancelRemovedMenuItem");
//					        	
//					        	eName.removeClassName("txtLineThrougt");
//					        } else {
//					        	e.removeClassName("cancelRemovedMenuItem");
//					        	e.addClassName("removeMenuItem");
//					        	
//					        	eName.addClassName("txtLineThrougt");
//					        }
//					        //TODO SMA Compute prorata des items du menu
				        } else {
//				        	//Check which basket has been selected
				        	if( receiverRowIndex == 0 && receiverColIndex == 0 ){
				        		if(!isMarketEditMode){
				        			unckedOppositeCheckBox();
				        			
						        	Element e = DOM.getElementById("checkbox." + idSuffix_);
									try {
										float basketPrice = Formatters.extractFloat( e.getAttribute("basketprice") );
										InputElement ie = InputElement.as(e);
										boolean isMenuChekced = ie.isChecked();
										
						        		updateMenuCount(idSuffix_, isMenuChekced);
						        		
							        	EventBusManager.getInstance().getEventBus().fireEvent(
					                			new CustomerOrderChangedEvent(ie.isChecked(), basketPrice));
									} catch (Exception e1) {
										e1.printStackTrace();
									}
						        	
//				        		for(MenuItem mi : menuItemList){
//				        			Element menuElem = DOM.getElementById("select.menuItem." + mi.getArticleName());
//				        			InputElement.as(menuElem).setChecked( isMenuChekced );
//				        		}
					        	
//				        		Element otherBasketElem = DOM.getElementById("checkbox." + htmlOtherBasketIdPrice_);
//				        		float otherBasketPrice = Float.parseFloat( otherBasketElem.getAttribute("basketPrice") );
//					        	InputElement otherBasketInputElement = InputElement.as(otherBasketElem);
//				        		if( otherBasketInputElement.isChecked() ){
//				        			EventBusManager.getInstance().getEventBus().fireEvent(
//				                			new CustomerOrderChangedEvent(false, 
//				                					otherBasketPrice));
//				        		}
//				        		InputElement.as(otherBasketElem).setChecked(false);
				        		
					        	
					        	}
				        		
					        }
					
				        }
			        }
				}
			}
		});

	}
	
//	private VLayout createBasketsPricePanel(){
//		VLayout vl = new VLayout();
//		vl.setAutoHeight();
//		vl.setAutoWidth();
//		
////		WidgetCanvas wcWholeBasketPrice = new WidgetCanvas( createBasketPricePanel( "Panier Entier", "wholeBasket", "halfBasket", true));
////		wcWholeBasketPrice.setAutoHeight();
////		wcWholeBasketPrice.setAutoWidth();
////		
//		WidgetCanvas wcHalfBasketPrice = new WidgetCanvas( createBasketPricePanel("Demi panier", "halfBasket", "wholeBasket", false));
//		wcHalfBasketPrice.setAutoHeight();
//		wcHalfBasketPrice.setAutoWidth();
//		
//		vl.setMembers(  wcHalfBasketPrice);//wcWholeBasketPrice, 
//		return vl;
//	}
//	
//	private SimplePanel createBasketPricePanel(String label_, String htmlIdPrice_, final String htmlOtherBasketIdPrice_, boolean isChecked_){
//		SimplePanel sp = new SimplePanel();
//		sp.addStyleName("slatePrice");
//		sp.add(createPriceFlexTable(label_, htmlIdPrice_, htmlOtherBasketIdPrice_, isChecked_));
//		return sp;
//	}
	
	private void updateMenuCount(String basketId_, boolean isSelected_){
		if( ! isSelected_ ){
			op.getOrderPartMenuItem().setMenuCount(MenuCount.ZERO_MENU);
		} else {
			if( basketId_.contains("wholeBasket") ){
				op.getOrderPartMenuItem().setMenuCount(MenuCount.ONE_MENU);
			} else if ( basketId_.contains("halfBasket") ){
				op.getOrderPartMenuItem().setMenuCount(MenuCount.HALF_MENU);
			}
		}
	}
//	private FlexTable createPriceFlexTable(final String label_, final String htmlIdPrice_, final String htmlOtherBasketIdPrice_, boolean isChecked_){
//		final FlexTable flexTable = new FlexTable();
//		flexTable.setWidth("130px");
//		flexTable.setCellPadding(0);
//		flexTable.setCellSpacing(0);
//		flexTable.setBorderWidth(0);
//		flexTable.addClickHandler(new ClickHandler() {
//			
//			@Override
//			public void onClick(ClickEvent event) {
//				Cell cell = flexTable.getCellForEvent(event);
//				if(cell!=null){
//			        int receiverRowIndex = cell.getRowIndex();
//			        int receiverColIndex = cell.getCellIndex();
//			        if( receiverRowIndex == 1 && receiverColIndex == 0 ){
//			        	Element e = DOM.getElementById("checkbox." + htmlIdPrice_);
//			        	float basketPrice = Float.parseFloat( e.getAttribute("basketPrice") );
//			        	boolean isMenuChekced = InputElement.as(e).isChecked();
//		        		for(MenuItem mi : menuItemList){
//		        			Element menuElem = DOM.getElementById("select.menuItem." + mi.getArticleName());
//		        			InputElement.as(menuElem).setChecked( isMenuChekced );
//		        		}
//			        	
//		        		Element otherBasketElem = DOM.getElementById("checkbox." + htmlOtherBasketIdPrice_);
//		        		float otherBasketPrice = Float.parseFloat( otherBasketElem.getAttribute("basketPrice") );
//			        	InputElement otherBasketInputElement = InputElement.as(otherBasketElem);
//		        		if( otherBasketInputElement.isChecked() ){
//		        			EventBusManager.getInstance().getEventBus().fireEvent(
//		                			new CustomerOrderChangedEvent(false, 
//		                					otherBasketPrice));
//		        		}
//		        		InputElement.as(otherBasketElem).setChecked(false);
//		        		
//		        		updateMenuCount(htmlIdPrice_, isMenuChekced);
//		        		
//			        	EventBusManager.getInstance().getEventBus().fireEvent(
//	                			new CustomerOrderChangedEvent(InputElement.as(e).isChecked(), 
//	                					basketPrice));
//			        }
//				}
//		        
//			}
//		});
//		
//		FlexCellFormatter fcf = (FlexCellFormatter) flexTable.getCellFormatter();
//		
//		flexTable.setHTML(0, 0, "");
//		fcf.setColSpan(0, 0, 2);
//		fcf.setHeight(0, 0, "25px");
//		String checked = "";
//		if(isChecked_){
//			checked = "checked=\"checked\"";
//		}
//		flexTable.setHTML(1, 0, "<form><input type=\"checkbox\" id=\"checkbox." + htmlIdPrice_ + "\"" + checked + "></input></form>");
//		flexTable.setHTML(1, 1, "<div class=\"slateBasketTxt\">" + label_ + "</div><div id=\"label." + htmlIdPrice_ + "\" class=\"priceTxt txtAlignCenter\">...</div>");
//		
//		fcf.setColSpan(0, 1, 2);
//		return flexTable;
//	}
		
	
	private void initTableHeader(final FlexTable table_, final String idSuffix_, String title_, float price_){
		FlexCellFormatter fcf = (FlexCellFormatter) table_.getCellFormatter();
		String basketPrice = price_<0?"loading...":Formatters.formatPrice(price_, false);
		if ( isMarketEditMode ){
			 
			Image img = new Image(PNResources.INSTANCE.editIcon());
			img.setStyleName("cursorHand");
			img.setTitle("Modifier le prix, ...");
			img.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					BasketPropertiesEditor bpe = new BasketPropertiesEditor(stall) {
						
						@Override
						protected void setMenuBasketPrice(float basketPrice_) {
							if( table_==flexTableFullBasket ){
								stall.getMenu().setWholePrice(basketPrice_);
							} else {
								stall.getMenu().setHalfPrice(basketPrice_);
							}
						}
						
						@Override
						protected void setMaxMenuBasket(int maxMenuBasket) {
							if( table_==flexTableFullBasket ){
								stall.setNbMaxWholeMenu(maxMenuBasket);
							} else {
								stall.setNbMaxHalfMenu(maxMenuBasket);
							}
						}
						
						@Override
						protected float getMenuBasketPrice() {
							if( table_==flexTableFullBasket ){
								return stall.getMenu().getWholePrice();
							} else {
								return stall.getMenu().getHalfPrice();
							}
						}
						
						@Override
						protected int getMaxMenuBasket() {
							if( table_==flexTableFullBasket ){
								return stall.getNbMaxWholeMenu();
							} else {
								return stall.getNbMaxHalfMenu();
							}
						}

						@Override
						protected void onPropertiesSaved(float basketPrice_,
								int maxMenuBasket) {
							Element div = DOM.getElementById( "label.edit.basket.price" + idSuffix_ );
							if(div!=null){
								div.setInnerHTML(Formatters.formatPrice(basketPrice_, true));
							}
						}
					};
				}
			});
			table_.setWidget(0, 0,  img);
		} else {
			String checked = "";
			if(table_==flexTableFullBasket){
				checked = "checked=\"checked\"";
			}
			table_.setHTML(0, 0, "<form><input type=\"checkbox\" id=\"checkbox." + idSuffix_ + "\" " + checked + " basketprice=\"" + basketPrice + "\"></input></form>");
		}
		
		table_.setHTML(0, 1, "<div style=\"margin:7px;\">" + 
								"<div class=\"slateTxt txtAlignCenter\" style=\"width:100%;\">" + title_ + "</div>" +
								"<div class=\"priceTxt txtAlignCenter\">" + 
									"<span id=\"label.edit.basket.price" + idSuffix_ + "\" >" + basketPrice + "</span>" +
									"<span id=\"label.edit.basket.price.currency" + idSuffix_ + "\" >&nbsp;" + Formatters.getCurrentCurrencyAsHtml() + "</span>" +
								"</div>" + 
							 "</div>");
		fcf.setColSpan(0, 1, 2);
		
        table_.setHTML(1, 0, "");
		table_.setHTML(1, 1, "<div class=\"txtAlignCenter\"><div class=\"slateMenuMiddleCenterSeparator\" style=\"margin-left:15px;\"></div></div>");
        fcf.setColSpan(1, 1, 2);
        
        table_.setHTML(2, 0, "");
        table_.setHTML(2, 1, "");
        table_.setHTML(2, 2, "");
		
	}
	
	private void checkResize(){
		int menuHalfSize = stall.getMenu().getMenuHalfItems().size();
		int menuWholeSize = stall.getMenu().getMenuWholeItems().size();
		
		int nbElements = menuWholeSize>menuHalfSize?menuWholeSize:menuHalfSize;
		setHeight(100 + 20*nbElements);
	}
	
	protected void initData(Stall stall_, OrderPart op_) {
		stall = stall_;
		op = op_;
		checkResize();
		initTableContents(flexTableFullBasketWidgetCanvas, flexTableFullBasket, stall.getMenu().getMenuWholeItems(),
				 "wholeBasket", "Panier de la semaine", stall.getMenu().getWholePrice() );
        
		initTableContents(flexTableHalfBasketWidgetCanvas, flexTableHalfBasket, stall.getMenu().getMenuHalfItems(),
				"halfBasket", "Demi panier", stall.getMenu().getHalfPrice());
        
		if(firstInit){
			if( ! isMarketEditMode ) {
		    	op.getOrderPartMenuItem().setMenuCount(MenuCount.ONE_MENU);
				op.getOrderPartMenuItem().setMenu(stall.getMenu());
				float computedPrice = op.computePrice().getValue();
				if( computedPrice  > 0){
					EventBusManager.getInstance().getEventBus().fireEvent(new CustomerOrderChangedEvent(true, computedPrice));
				}
	    	}
			
			firstInit = false;
		}
	}
	
	private void clearAllProductsFromTable(FlexTable flexTableBasket_){
		for(int i=flexTableBasket_.getRowCount()-1; i>3; i--){
			flexTableBasket_.removeRow(i);
		}
	}
	
	private void initTableContentsHeader(WidgetCanvas parentCanvas_, FlexTable flexTableBasket_, List<MenuItem> menuItemList_, String idSuffix_, String title_, float price_){
		if ( menuItemList_.size()>0 ){
			flexTableBasket_.removeAllRows();
			initTableHeader(flexTableBasket_, idSuffix_, title_, price_);
		} else {
			if( ! isMarketEditMode ){
				parentCanvas_.setVisible(false);
			}
		}
	}
	
	private void initTableContentsProductsList(FlexTable flexTableBasket_, 
			List<MenuItem> menuItemList_, String idSuffix_){
		clearAllProductsFromTable(flexTableBasket_);
		int i=3;
    	for (MenuItem p : menuItemList_) {
			try{
				//price + " &#8364; / " + 
//				String price = nf.format(p.getMenuProductPrice() );
				String name = p.getArticleName();
				String variety = p.getOnSaleProduct().getProduct().getProductVariety().getName();
				String category = p.getOnSaleProduct().getProduct().getProductVariety().getProductCategory().getName();
				String quantity = new Float( p.getQuantity().getValue()).toString();
				if(quantity=="1"){
					quantity="";
				}
				String quantityUnit = p.getQuantity().getUnitAsEnum().getDisplayName();
				
				setTableRowContent(flexTableBasket_, i, idSuffix_, name, name, quantity, quantityUnit, p);
				i++;
			} catch (NullPointerException e_) {
				GWT.log("Err on displaySellSessionForCustomer ", e_);
			}
		}
    	if( isMarketEditMode ){
    		setTableRowContent(flexTableBasket_, i, idSuffix_, NEW_ITEM_ID, "Nouveau produit", "", "", null);
    	}
	}
	
	private void initTableContents(WidgetCanvas parentCanvas_, FlexTable flexTableBasket_, List<MenuItem> menuItemList_,
			String idSuffix_, String title_, float price_
			) {
		initTableContentsHeader(parentCanvas_, flexTableBasket_, menuItemList_, idSuffix_, title_, price_);
		initTableContentsProductsList(flexTableBasket_, menuItemList_, idSuffix_);
	}
	
	private void setTableRowContent(final FlexTable flexTableBasket_, int rowIdex_, String idSuffix_, 
			String menuItemId_, final String menuItemName_,
			String quantity_, String quantityUnit_,
			final MenuItem menuItem_){
		if ( isMarketEditMode ){
			final boolean isANewItem = menuItemId_.equalsIgnoreCase(NEW_ITEM_ID);
			ImageResource ir = isANewItem?PNResources.INSTANCE.addIcon():
				PNResources.INSTANCE.deleteIcon();
			
			Image img = new Image( ir );
			img.setStyleName("cursorHand");
			img.setAltText(isANewItem?"Ajouter le produit...":"Supprimer le produit...");
			img.setTitle(isANewItem?"Ajouter le produit...":"Supprimer le produit...");
			img.addClickHandler(new ClickHandler() {
				
				private void removeProduct(){
					SC.ask("Confirmation de suppression de produit", 
						"Supprimer le produit \"" + menuItemName_ + "\" ?", 
						new BooleanCallback() {
						
						@Override
						public void execute(Boolean value_) {
							if( value_ ){
								Menu m = stall.getMenu();
								int menuItemRow = -1;
								FlexTable curFlexTableBasket = null;
								MenuItem mi = null;
								if( flexTableBasket_ == flexTableFullBasket ){
									curFlexTableBasket = flexTableFullBasket;
									mi = m.findWholeMenuItemFor(menuItemName_);
									if( mi != null){
										stall.getMenu().getMenuWholeItems().remove(mi);
									}
								} else {
									curFlexTableBasket = flexTableHalfBasket;
									mi = m.findHalfMenuItemFor(menuItemName_);
									if( mi != null){
										stall.getMenu().getMenuHalfItems().remove(mi);
									}
								}
								
								if( mi != null){
									menuItemRow = findRowOfProduct(curFlexTableBasket,  mi);
									
									if( menuItemRow>=0 && menuItemRow<curFlexTableBasket.getRowCount()){
										curFlexTableBasket.removeRow( menuItemRow );
									}
									
									saveOnServer();
								}
							}
						}

						
					});
				}
				
				
				@Override
				public void onClick(ClickEvent event) {
					if( isANewItem ){
						new ProductMarketEditionWindow(stall, null, null, true){

							protected MenuItem updateMenuItem(MenuItem mi, String newProductName_, String oldProductName_, Float newQuantite_, Float oldQuantite_,
									String newQuantiteUnit_, String oldQuantiteUnit){
								if(newProductName_ != null && ! newProductName_.equalsIgnoreCase(oldProductName_)){
									Product selProduct = this.getSelectedProduct();
									if(selProduct!=null){
										mi.getOnSaleProduct().setProduct( selProduct );
									}
								}
								Quantity qty = createQuantity(newQuantite_, oldQuantite_, newQuantiteUnit_, oldQuantiteUnit);
								mi.setQuantity(qty);
								mi.getOnSaleProduct().setPrice(new Price(0f, qty));
								return mi;
							}
							
							private MenuItem checkMenuItemCreated(boolean isWHoleBasket_, MenuItem mi_){
								MenuItem mi = mi_;
								if( mi ==null ){
									mi = new MenuItem();
									mi.setId(new Date().getTime());
									mi.setOnSaleProduct(new OnSaleProduct());
									if( isWHoleBasket_ ){
										stall.getMenu().addMenuWholeItem(mi);
									} else {
										stall.getMenu().addMenuHalfItem(mi);
									}
								}
								return mi;
							}
							
							@Override
							protected void onValidateAction(
									Product newProduct_,
									String oldProductName_, Float newPrice_,
									Float oldPrice_, Float newQuantite_,
									Float oldQuantite_, String newQuantiteUnit_,
									String oldQuantiteUnit_) {
								MenuItem mi = null;
								String idSuffix = null;
								List<MenuItem> miList = null;
								if( flexTableBasket_ == flexTableFullBasket ){
									mi = checkMenuItemCreated( true, stall.getMenu().findWholeMenuItemFor(newProduct_.getName()) );
									updateMenuItem(mi, newProduct_.getName(), oldProductName_,
											newQuantite_, oldQuantite_, newQuantiteUnit_, oldQuantiteUnit_);
									miList = stall.getMenu().getMenuWholeItems();
									idSuffix = "wholeBasket";
								} else {
									mi = checkMenuItemCreated( false, stall.getMenu().findHalfMenuItemFor(newProduct_.getName()) );
									updateMenuItem(mi, newProduct_.getName(), oldProductName_,
											newQuantite_, oldQuantite_, newQuantiteUnit_, oldQuantiteUnit_);
									miList = stall.getMenu().getMenuHalfItems();
									idSuffix = "halfBasket";
								}
								saveOnServer(true, flexTableBasket_, miList, idSuffix);
							}
							
						};
					} else {
						removeProduct();
					}
				}
			});
			flexTableBasket_.setWidget(rowIdex_, 0,  img);
		} else {
			flexTableBasket_.setHTML(rowIdex_, 0, "");//"<form><input type=\"checkbox\" id=\"select.menuItem." + idSuffix_ + "." + "newItem\" checked=\"checked\"></input></form>");
		}
		flexTableBasket_.setHTML(rowIdex_, 1, "<span class=\"slateTxt\" id=\"name.menuItem." + idSuffix_ + "." + menuItemId_ + "\">" + menuItemName_ + "</span>");
		flexTableBasket_.setHTML(rowIdex_, 2, "<span class=\"slateTxt\">" + quantity_ + "&nbsp;"  + quantityUnit_ + "</span>");
	}
	
	private int findRowOfProduct(
			FlexTable curFlexTableBasket_,
			MenuItem menuItem_) {
		if(curFlexTableBasket_ != null && menuItem_!=null){
			for(int i=0;i<curFlexTableBasket_.getRowCount();i++){
				if( curFlexTableBasket_.getHTML(i, 1).contains( menuItem_.getOnSaleProduct().getProduct().getName() ) ){
					return i;
				}
			}
		}
		return -1;
	}
	
	private void saveOnServer(){
		this.saveOnServer(false, null, null, null);
	}
	
	private void saveOnServer(final boolean reinitProductList_, 
			final FlexTable flexTableBasket_,
			final List<MenuItem> menuItemList_,
			final String idSuffix_){
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		final SaveStallCallback saveStallCallback = new SaveStallCallback(stall);
		callSequencer.addCall(saveStallCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				if(reinitProductList_){
					initTableContentsProductsList(flexTableBasket_, menuItemList_, idSuffix_);
				}
				checkResize();
			}
		});
		callSequencer.callSequence();
	}
}
